<template>
  <div class="creat-wrapper">
    <el-form class="look" v-if="typePage && typePage === 'look'" label-position="right" :model="ruleForm" :rules="rulesList" ref="ruleForm" label-width="180px">
      <el-form-item v-for="(item, index) in formInfo"
                    v-if="item.prop !== 'street'"
                    :key="index" 
                    :label="item.localIndex ? (item.label + item.localIndex) + ' :' : item.label + ' :'" 
                    :prop="item.prop">
        <!-- <div class="part" v-if="(index ===0 || (item.add && item.localIndex == 1)) && ishow">{{index ===0 && '基本信息' || (item.add && item.localIndex == 1) && '打款人信息'}}</div> -->
        <span v-if="item.type === 'input' && item.prop !== 'street'">{{ruleForm[item.prop]}}</span>
        <el-radio-group v-if="item.type === 'radio'" v-model="ruleForm[item.prop]">
          <el-radio v-for="(op, opIndex) in item.radioOptions" :key="opIndex" :label="op.label">{{op.name}}</el-radio>
        </el-radio-group>
        <span v-if="item.type === 'select'">{{ruleForm[item.propName]}}</span>
        <div v-if="item.type === 'selectProvince' && item.child && ruleForm.provinceName">{{ruleForm.provinceName + ruleForm.cityName + ruleForm.countyName + ruleForm.street}}
        </div>
        <el-switch v-if="item.type === 'switch'" v-model="ruleForm[item.prop]"></el-switch>
        <div v-if="item.type === 'remit'" class="remit_part">{{ruleForm[item.prop]}}</div>
        <el-checkbox v-if="item.type === 'checkout'" v-model="ruleForm[item.prop]"></el-checkbox>
        <!-- 共享方案组 -->
        <!-- <div v-if="item.type === 'shareArea'">
          <el-table
            :data="shareData"
            stripe
            style="width: 100%">
            <el-table-column
              prop="groupNo"
              label="共享方案组编号">
            </el-table-column>
            <el-table-column
              prop="name"
              label="共享方案组名称">
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
                <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-autocomplete
            v-model="state"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            @select="handleSelect" style="width: 100%;"
          ></el-autocomplete>
        </div>
        <div v-if="item.type === 'limitArea'">
          <el-tree
            ref="menuListTree"
            :data="datas"
            show-checkbox
            node-key="id"
            :props="defaultProps" @check-change="handleCheckChange">
          </el-tree>
        </div> -->
      </el-form-item>
      <el-button style="margin-left: 100px;" @click="onCancel('ruleForm')">返回</el-button>
    </el-form>
    <el-form v-else label-position="right" :model="ruleForm" :rules="rulesList" ref="ruleForm" label-width="180px" class="creat-wrapper_form">
      <el-form-item v-for="(item, index) in formInfo"
                    :key="index" :label="item.localIndex ? (item.label + item.localIndex) : item.label" 
                    :prop="item.prop" 
                    :class="(index ===0 || (item.add && item.localIndex === 1)) && ishow ? 'mt60' : ''" :required="isHaveTo">
        <div class="part" v-if="(index ===0 || (item.add && item.localIndex == 1)) && ishow">{{index ===0 && '基本信息' || (item.add && item.localIndex == 1) && '打款人信息'}}</div>
        <el-input v-if="item.type === 'input'"
                  :type="item.inputType"  
                  v-model="ruleForm[item.prop]"
                  :placeholder="'请输入' + item.name"
                   clearable
                  :disabled="isEditPage && item.isDisable" style="width: 60%;">
          <template v-if="item.iconEnd" slot="append">%</template>
        </el-input>
        <el-radio-group v-if="item.type === 'radio'" v-model="ruleForm[item.prop]">
          <el-radio v-for="(op, opIndex) in item.radioOptions" :key="opIndex" :label="op.label">{{op.name}}</el-radio>
        </el-radio-group>
        <el-select v-if="item.type === 'select'"
                   style="width: 60%"
                   v-model="ruleForm[item.prop]"
                   :disabled="item.prop === 'parentCode' && ruleForm.productClass && ruleForm.productClass === '大分类'"
                   clearable
                   filterable
                   :placeholder="'请选择' + item.name"
                   @change="(val) => onChangeSelect(val, {code: item.prop, name: item.propName, valueName: item.optionLabel, valueCode: item.optionValue})">
          <el-option v-for="(county, currentIndex) in countylist[item.prop]"
                       :label="`${item.joint ? county[item.optionValue] + '/' : ''}${county[item.optionLabel]}`"
                       :key="currentIndex"
                       :value="county[item.optionValue]"></el-option>
        </el-select>
        <area-cascader v-if="item.type === 'selectProvince'" class="address" 
                        v-model="currentAddress" 
                        :data="pcaa" 
                        :level="1" 
                        type="all" 
                        :placeholder="'请选择' + item.name"
                        @change="onAddressChange" />
                        <!-- <span>{{currentAddress}}</span> -->
        <!-- <div v-if="item.type === 'selectProvince' && item.child" style="width: 60%;">
          <span class="m-r-10">
            <el-select v-model="provinceName" placeholder="省" @change="onChangeProvince" clearable filterable style="width: 32.5%;">
              <el-option v-for="(province, indexPro) in provinceList.province" :key="indexPro" :label="province" :value="indexPro">
              </el-option>
            </el-select>
            <el-select v-model="cityName" placeholder="市" @change="onChangeCity" clearable filterable style="width: 32.6%;">
              <el-option v-for="(city, indexCity) in cityList" :key="indexCity" :label="city" :value="indexCity">
              </el-option>
            </el-select>
            <el-select v-model="countyName" placeholder="区县" @change="onChangeCounty" clearable filterable style="width: 32%;">
              <el-option v-for="(count, indexCounty) in countryList" :key="indexCounty" :label="count" :value="indexCounty">
              </el-option>
            </el-select>
          </span>
        </div> -->
        <el-switch v-if="item.type === 'switch'" v-model="ruleForm[item.prop]"></el-switch>
        <div v-if="item.type === 'remit'" class="remit_part">
          <el-input v-model="ruleForm[item.prop]" :placeholder="'请输入' + item.label" clearable style="width: 60%;"></el-input><span v-if="item.add" class="el-icon-circle-plus-outline add_btn" @click="onAdd"></span>
        </div>
        <el-checkbox v-if="item.type === 'checkout'" v-model="ruleForm[item.prop]"></el-checkbox>
        <!-- 共享方案组 -->
        <div v-if="item.type === 'shareArea'">
          <el-table
            :data="shareData"
            stripe
            style="width: 100%">
            <el-table-column
              prop="groupNo"
              label="共享方案组编号">
            </el-table-column>
            <el-table-column
              prop="name"
              label="共享方案组名称">
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
                <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-autocomplete
            v-model="state"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            @select="handleSelect" style="width: 100%;"
          ></el-autocomplete>
        </div>
        <div v-if="item.type === 'limitArea'">
          <el-tree
            ref="menuListTree"
            :data="datas"
            show-checkbox
            node-key="id"
            :props="defaultProps" @check-change="handleCheckChange">
          </el-tree>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onConfirm('ruleForm')">确认</el-button>
        <el-button type="info" @click="onCancel('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {getSelectName} from '@/common/utils'
import {cloneDeep} from 'lodash'
import threeData from './data.json'
import { pcaa } from 'area-data'
export default {
  name: 'form-marker',
  props: {
    isEdit: Boolean,
    formData: {
      type: Array
    },
    rulesList: {
      type: Object
    },
    isShowTitle: {
      type: Boolean
    },
    selectList: {
      type: Object
    },
    eidtList: {
      type: Object
    }
  },
  data () {
    return {
      formInfo: this.formData,
      ishow: this.isShowTitle,
      // ruleForm: this.eidtList,
      // countylist: this.selectList,
      count: 1,
      provinceList: {},
      cityList: null,
      countryList: null,
      provinceName: null,
      cityName: null,
      countyName: null,
      shareData: [],
      restaurants: [],
      state: '',
      timeout: null,
      datas: [],
      limitData: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        value: 'id'
      },
      num: 1,
      // pac: pac,
      pcaa: pcaa,
      address: '',
      currentAddress: [],
      typePage: '' // 页面类型
    }
  },
  computed: {
    isEditPage: function () {
      // console.log('this.isEdit', this.isEdit, this.selectList.limitData)this.pageType = this.$route.params.id
      return this.isEdit
    },
    countylist: {
      get () {
        if (this.selectList.limitData) {
          let curLimit = cloneDeep(this.selectList.limitData)
          this.lookPermission(curLimit)
        }
        // let list = this.selectList.shopHeaderAccountable ? this.selectList.shopHeaderAccountable : []
        // this.restaurants = list.map((val) => {
        //   val.value = val.name
        //   return val
        // })
        return this.selectList
      },
      set (val) {
        this.selectList = val
      }
    },
    ruleForm: {
      get () {
        this.provinceName = this.eidtList.provinceName && this.eidtList.provinceName
        this.cityName = this.eidtList.cityName && this.eidtList.cityName
        this.countyName = this.eidtList.countyName && this.eidtList.countyName
        this.cityList = this.eidtList.provinceNo && threeData[this.eidtList.provinceNo]
        this.countryList = this.eidtList.cityNo && threeData[this.eidtList.cityNo]
        this.shareData = this.eidtList.shareSchemeGroups ? this.eidtList.shareSchemeGroups : []
        this.setAddress(this.eidtList)
        return this.eidtList
      }
    },
    isHaveTo: function () {
      return this.ruleForm && this.ruleForm.productClass && this.ruleForm.productClass === '小分类'
    }
  },
  watch: {
    formData: function (currentValue) {
      this.formInfo = currentValue
    },
    isEditPage: function (currentValue) {
      if (currentValue && this.ruleForm.permissions) {
        let curLimitList = cloneDeep(this.ruleForm.permissions)
        this.lookPermission(curLimitList)
      }
    }
  },
  created () {
    this.typePage = this.$route.params.id || ''
  },
  mounted () {
    this.provinceList = threeData
  },
  methods: {
    onChangeSelect (val, params) {
      let currentSelectList = cloneDeep(this.countylist[params.code])
      this.ruleForm[params.code] = val
      this.ruleForm[params.name] = getSelectName(val, params, currentSelectList)
      if (params.name === 'productClass') { // 商品分类存在类别，上级区域必填及联
        if (this.ruleForm[params.name] === '大分类') {
          this.ruleForm.parentCode = ''
          this.ruleForm.parentName = ''
        }
        this.$emit('change-rule', {isHaveTo: this.isHaveTo, parentCode: this.ruleForm.parentCode, productClass: this.ruleForm.productClass})
        // this.$refs['parentCategory'][0].clearValidate()
      }
    },
    onChangeProvince (val) {
      // console.log('onChangeProvince', val)
      this.cityList = this.provinceList[val]
      this.provinceName = this.provinceList.province[val]
      this.ruleForm.provinceName = this.provinceName
      this.ruleForm.provinceNo = val
      this.cityName = ''
      this.ruleForm.cityName = ''
      this.ruleForm.cityNo = ''
      this.countyName = ''
      this.ruleForm.countyName = ''
      this.ruleForm.countyNo = ''
    },
    onChangeCity (val) {
      // console.log('onChangeCity', val)
      this.countryList = this.provinceList[val]
      this.cityName = this.cityList[val]
      this.ruleForm.cityName = this.cityName
      this.ruleForm.cityNo = val
      this.countyName = ''
      this.ruleForm.countyName = ''
      this.ruleForm.countyNo = ''
    },
    onChangeCounty (val) {
      // console.log('onChangeCounty 111', val)
      this.countyName = this.countryList[val]
      this.ruleForm.countyNo = val
      this.ruleForm.countyName = this.countyName
      this.$emit('on-address', {provinceName: this.ruleForm.provinceName, cityName: this.ruleForm.cityName, countyName: this.ruleForm.countyName})
    },
    onSave () {
      let moreParams = {}
      if (this.$route.name === 'createCompany') {
        moreParams.shareSchemeGroups = this.getShareItem()
        moreParams.permissionCodes = this.setPermission()
        // this.$emit('on-confirm', this.ruleForm, moreParams)
      }
      this.$emit('on-confirm', this.ruleForm, moreParams)
    },
    onConfirm (formName) { // 确认
      if (this.$route.name === 'createBrand' && !this.ruleForm.name && !this.ruleForm.enName) {
        this.$emit('on-whiice-one', true)
      }
      this.$refs[formName].validate((valid) => {
        // console.log('valid', valid)
        if (valid) {
          this.onSave()
        } else {
          return false
        }
      })
    },
    onCancel () { // 取消
      this.$emit('on-cancel')
    },
    onAdd () {
      if (this.count < 3) {
        this.count ++
      } else {
        return
      }
      let name = {type: 'remit', label: '常用打款人', prop: 'accontName' + this.count, add: true, localIndex: this.count}
      let bank = {type: 'remit', label: '开户银行', prop: 'bank' + this.count, localIndex: this.count}
      let account = {type: 'remit', label: '银行账户', prop: 'account' + this.count, localIndex: this.count}
      this.formInfo = this.formInfo.concat(name, bank, account)
    },
    querySearchAsync (queryString, callback) {
      this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/shareSchemeGroup/listShareSchemeGroup`, {name: queryString}, {loading: false}).then((res) => {
        let list = res.data
        this.restaurants = list.map((val) => {
          val.value = val.name
          return val
        })
        callback(this.restaurants)
        // clearTimeout(this.timeout)
        // this.timeout = setTimeout(() => {
        //   callback(this.restaurants)
        // }, 300 * Math.random())
      })
      // var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants
      // // console.log('results', results)
    },
    createStateFilter (queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleSelect (val) {
      let cum = this.shareData.length > 0 ? this.shareData.map(v => v.code) : [val.code]
      if (this.shareData.length === 0 || !cum.includes(val.code)) {
        this.shareData = this.shareData.concat(val)
      }
    },
    getShareItem () {
      let obj = null
      obj = this.shareData.map((val) => {
        return {groupNo: val.groupNo, name: val.name, shareSchemeCode: val.shareSchemeCode, code: val.code}
      })
      return obj
    },
    onDelete (val) {
      this.shareData = this.shareData.filter(v => v.groupNo !== val.groupNo)
    },
    handleCheckChange () {},
    handleNodeClick () {},
    lookPermission (pa) {
      // console.log('pa ====', pa)
      let cur = cloneDeep(pa)
      this.nodes = []
      this.datas = this.treeDataTranslate(cur, 'code', 'parentCode')
      this.getNodes(this.datas)
      this.$nextTick(() => {
        this.$refs.menuListTree[0].setCheckedKeys(this.nodes)
      })
    },
    // 递归获取节点
    getNodes (treenodes) {
      if (treenodes.length > 0) {
        for (let i = 0; i < treenodes.length; i++) {
          if (treenodes[i].children) {
            this.getNodes(treenodes[i].children)
          } else {
            if (treenodes[i].selected) {
              this.nodes.push(treenodes[i].id)
            }
          }
        }
      }
    },
    treeDataTranslate (data, id = 'code', pid = 'parentCode') {
      let res = []
      let temp = {}
      if (data && data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          temp[data[i][id]] = data[i]
        }
        for (let k = 0; k < data.length; k++) {
          if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
            if (!temp[data[k][pid]]['children']) {
              temp[data[k][pid]]['children'] = []
            }
            if (!temp[data[k][pid]]['level']) {
              temp[data[k][pid]]['level'] = 1
            }
            data[k]['level'] = temp[data[k][pid]].level + 1
            temp[data[k][pid]]['children'].push(data[k])
          } else {
            res.push(data[k])
          }
        }
      }
      return res
    },
    setPermission () {
      let keyList = this.$refs.menuListTree[0].getCheckedNodes()
      let halfKeyList = this.$refs.menuListTree[0].getHalfCheckedNodes()
      let result = keyList.concat(halfKeyList).map(item => item.code)
      return result
    },
    onAddressChange (val) {
      let currentData = cloneDeep(val)
      currentData.map((v, k) => {
        let keys = Object.keys(v).toString()
        let values = Object.values(v).toString()
        this.ruleForm.provinceName = k === 0 ? values : this.ruleForm.provinceName
        this.ruleForm.provinceNo = k === 0 ? keys : this.ruleForm.provinceNo
        this.ruleForm.cityName = k === 1 ? values : this.ruleForm.cityName
        this.ruleForm.cityNo = k === 1 ? keys : this.ruleForm.cityNo
        this.ruleForm.countyName = k === 2 ? values : this.ruleForm.countyName
        this.ruleForm.countyNo = k === 2 ? keys : this.ruleForm.countyNo
      })
      this.$emit('on-address', {provinceName: this.ruleForm.provinceName, cityName: this.ruleForm.cityName, countyName: this.ruleForm.countyName})
    },
    setAddress (pa) {
      if (pa && pa.provinceNo) {
        this.currentAddress.push(pa.provinceNo)
      }
      if (pa && pa.cityNo) {
        this.currentAddress.push(pa.cityNo)
      }
      if (pa && pa.countyNo) {
        this.currentAddress.push(pa.countyNo)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.creat-wrapper{
  background: white;
  padding: 10px 0;
  &_base{
    margin-left: 30px;
    border-left: 5px #409EFF solid;
  }
  &_form{
    padding: 20px 250px;
    .mt60{
      margin-top: 60px;
    }
    .part{
      position: absolute;
      left: -360px;
      top: -60px;
      border-left: 5px #409EFF solid;
      font-size: 16px;
      height: 16px;
      line-height: 16px;
      padding-left: 5px;
    }
  }
  .remit_part{
    position: relative;
    .add_btn{
      position: absolute;
      left: 60%;
      top: 10%;
      font-size: 30px;
      color: #409EFF;
    }
  }
  .look{
    padding-left: 80px;
  }
  
	/deep/ .large{
    width: 60%;
    height: 90%;
  }
	 /deep/.area-select{
    height: 36px;
	}
	
	/deep/ .area-select .area-selected-trigger{
    padding: 0px 20px 0 12px;
    color: #666;
	}
}
</style>